package com.yjd.bi.statistic.control;

import com.yjd.bi.borrow.model.BorrowCountModel;
import com.yjd.bi.borrow.service.IArrearsFormService;
import com.yjd.bi.business.service.IInvestInfoService;
import com.yjd.bi.comm.utils.BiDateUtil;
import com.yjd.bi.report.enums.TimeType;
import com.yjd.bi.report.model.EChartsModel;
import com.yjd.comm.annotation.ServiceRemoteProxy;
import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.rpm.RpmServiceKeyEnum;
import com.yjd.comm.util.ArithUtil;
import com.yjd.comm.util.DateUtil;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.NumberUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Scope("prototype")
@RequestMapping("/borrow/")
public class BorrowControl extends BaseControl {
	
	@ServiceRemoteProxy(serviceUrlResouceKey=RpmServiceKeyEnum.RPM_BI_SERVICE_KEY)
	IArrearsFormService arrearsFormService;
	@ServiceRemoteProxy(serviceUrlResouceKey = RpmServiceKeyEnum.RPM_BI_SERVICE_KEY)
	IInvestInfoService investInfoService;
	
	/**
	 * 根据yyyy-MM-dd转为long格式的yyyyMMdd
	 * @return
	 */
	public String getTime(String time){
		return DateUtil.timestampToDateString(DateUtil.dateStringToTimestamp(time, DateUtil.PATTERN_yyyy_MM_dd), DateUtil.PATTERN_yyyyMMdd);
	}
	
	@RequestMapping("index")
	public String deal() throws Exception {
        request.setAttribute("start", "2013-12-21");
        request.setAttribute("now", BiDateUtil.initBiDate());
		request.setAttribute("t1", BiDateUtil.getT1Date());
		request.setAttribute("t7", BiDateUtil.getT7Date());
		return "borrow.index";
	}
	
	@RequestMapping("getSummary")
	public void getIndexData(String start,String end) throws Exception {
		try{
			start=getTime(start);
			end=getTime(end);
		}catch(Exception e){
			this.errorMsg("参数有误！");
			return;
		}

		Long startTime = DateUtil.dateStringToTimestamp(start, DateUtil.PATTERN_yyyyMMdd);
		Long endTime = DateUtil.dateStringToTimestamp(end, DateUtil.PATTERN_yyyyMMdd)+86399;

		//代偿本金
		Double capital=this.arrearsFormService.getSumPrice("SUM(a.capital)",startTime,endTime,0);
		//代偿本金笔数
		Double Alltimes=this.arrearsFormService.getSumPrice("count(*)",startTime,endTime,1);
		//代偿利息
		Double interest=this.arrearsFormService.getSumPrice("SUM(a.interest)",startTime,endTime,0);
		//代偿利息笔数
		Double interest_times=this.arrearsFormService.getSumPrice("count(*)",startTime,endTime,2);
		//借款用户数
		Long userCount=this.arrearsFormService.getBorrowerCount(startTime, endTime);

		this.successData(FrameUtil.newHashMap("summaryVals",FrameUtil.newArrayList(capital,Alltimes,interest,interest_times,userCount)));
	}
	
	@RequestMapping("/top10")
	public void getTop10(String time) throws Exception{
		Long stime=0l;
		try{
			stime=DateUtil.dateStringToTimestamp(time, DateUtil.PATTERN_yyyy_MM_dd)+23*60*60+59*60+59;
		}catch(Exception e){
			this.errorMsg("参数有误！");
			return;
		}
		List<BorrowCountModel> result=this.arrearsFormService.getRecoveryByTime(stime);
		Double sum=0.0;
		Double t_sum=0.0;
		List<Map<String, String>> topList=FrameUtil.newArrayList();
		List<String> names=FrameUtil.newArrayList();
		for(BorrowCountModel m:result){
			if(topList.size()<10){
				topList.add(FrameUtil.newHashMap("value",m.getPrice(),"name",m.getUsername()));
				names.add((String) m.getUsername());
				t_sum+=m.getPrice();
			}else{
				sum+=  m.getPrice();
			}
		}
		if(sum.doubleValue()>0.0){
			topList.add(FrameUtil.newHashMap("value", sum,"name","其余"));
			names.add("其余");
		}
		this.successData(FrameUtil.newHashMap("data",topList,"names",names,"t_sum",t_sum+sum));
	}

	/**
	 * 获取初始数据
	 * @param timeType
	 * @param timeFrom
	 * @throws Exception
	 */
	@RequestMapping("getDatasByField")
	public void getDatas(String timeType,String timeFrom,String field) throws Exception{
		try{
			timeFrom=DateUtil.timestampToDateString(DateUtil.dateStringToTimestamp(timeFrom, DateUtil.PATTERN_yyyy_MM_dd),"yyyyMMdd");
			TimeType.getType(Integer.parseInt(timeType));
			Long.parseLong(timeFrom);
		}catch(Exception e){
			this.errorMsg("参数有误！");
		}
		TimeType t=TimeType.getType(Integer.parseInt(timeType));
		EChartsModel ec=this.arrearsFormService.getDates(t, Long.parseLong(timeFrom), field);
		this.successData(FrameUtil.newHashMap("option",ec));
	}

	/**
	 *
	 * @param end
	 * @throws Exception
	 */
	@RequestMapping("getSummaryOverdue")
	public void getSummaryOverdue(String end) throws Exception {
		try{
			end=getTime(end);
		}catch(Exception e){
			this.errorMsg("参数有误！");
			return;
		}
		long endtime = DateUtil.dateStringToTimestamp(end, DateUtil.PATTERN_yyyyMMdd)+23*60*60+59*61;
		//90天以上本金代偿余额－借款
		Double capital=this.arrearsFormService.fieldSelect("sum(capital)", endtime,0);
		//90天以上本金代偿笔数－借款
		Double capital_times=this.arrearsFormService.fieldSelect("count(*)", endtime,1);
		//90天以上利息代偿余额－借款
		Double interest=this.arrearsFormService.fieldSelect("sum(interest)", endtime,0);
		//90天以上利息代偿笔数－借款
		Double interest_times=this.arrearsFormService.fieldSelect("count(*)", endtime,2);
		//90天以上逾期率    = 上本金代偿余额/待回收金额（含代偿余额）

		//待回收金额（含代偿余额）－投资项目
		double recover_price =  this.arrearsFormService.getRecoverPrice(endtime);
		String overdue_rate = NumberUtil.formatNumber3(ArithUtil.div(capital, recover_price)*100);
		//90天以上累计逾期率 = 本金代偿余额/截止到该时间点平台投资项目累计成交额（按照满标终审时间计算）
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("start", FrameUtil.getTime(DateUtil.parseDate("20131221", DateUtil.PATTERN_yyyyMMdd)));
		paramMap.put("end", FrameUtil.getTime(DateUtil.parseDate(end, DateUtil.PATTERN_yyyyMMdd))+86400);
		//投资项目累计成交额
		Double total_invest_price = (Double) investInfoService.getInvestPriceOver(paramMap);

		//累计逾期率
		String total_overdue_reate = NumberUtil.formatNumber3(ArithUtil.div(capital, total_invest_price)*100);

		this.successData(FrameUtil.newHashMap("summaryVals",FrameUtil.newArrayList(capital,capital_times,interest,interest_times,overdue_rate,total_overdue_reate)));
	}
	
	@RequestMapping("getExpectPrice")
	public void getExpectPrice(String start,String end,Integer depo_type,Integer dz_type) throws Exception {
		try{
			start=getTime(start);
			end=getTime(end);
		}catch(Exception e){
			this.errorMsg("参数有误！");
			return;
		}

		Long startTime = DateUtil.dateStringToTimestamp(start, DateUtil.PATTERN_yyyyMMdd);
		Long endTime = DateUtil.dateStringToTimestamp(end, DateUtil.PATTERN_yyyyMMdd)+86399;

		//预计到期金额
		Double expect_price=this.arrearsFormService.getExpectPrice(startTime,endTime,depo_type,dz_type);

		this.successData(FrameUtil.newHashMap("summaryVals",FrameUtil.newArrayList(expect_price)));
	}
}
